﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.IdentityModel.Logging;

namespace SendMessagePage.Util
{
    public class AccessWebApiUtil
    {
        #region post请求

        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="data">发送的参数字符串</param>
        /// <returns>返回的字符串</returns>
        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="json">发送的参数字符串，只能用json</param>
        /// <returns>返回的字符串</returns>
        public static async Task<string> PostAsyncJson(string url, string json)
        {
            string responseBody = string.Empty;
            using (HttpClient client = new HttpClient())
            {
                HttpContent content = new StringContent(json);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                //request.Headers.Authorization = new AuthenticationHeaderValue("Authorization", token);
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);

                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        responseBody = await response.Content.ReadAsStringAsync();
                    }
                }
                catch (Exception)
                {

                    throw;
                }


            }
            Console.WriteLine(responseBody);
            return responseBody;
        }



        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="data">发送的参数字符串</param>
        /// <returns>返回的字符串</returns>
        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="json">发送的参数字符串，只能用json</param>
        /// <returns>返回的字符串</returns>
        public static async Task<string> PostAsyncJson(string url, string json, string token)
        {
            string responseBody = string.Empty;

            try
            {
                // 创建一个HttpRequestMessage对象
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);

                // 设置请求头
                request.Headers.Add("Authorization", "Bearer " + token);


                // 设置请求内容（如果需要）
                request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

                HttpClient client = new HttpClient();


                HttpResponseMessage response = await client.SendAsync(request);


                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine("Error: " + response.StatusCode);
                }
                return responseBody;
            }
            catch (Exception)
            {

                MessageBox.Show("出现未知错误", "提示信息");
            }

            return responseBody;


        }


        #endregion

        #region get请求
        /// <summary>
        /// 使用Get请求异步获取信息
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <returns></returns>
        public static async Task<string> GetStringAsync(string url)
        {

            string responseBody = string.Empty;
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };

            using (var httpclient = new HttpClient(handler))
            {
                httpclient.BaseAddress = new Uri(url);
                httpclient.DefaultRequestHeaders.Accept.Clear();
                httpclient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await httpclient.GetAsync("");

                if (response.IsSuccessStatusCode)
                {
                    Stream myResponseStream = await response.Content.ReadAsStreamAsync();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    string retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                    responseBody = await response.Content.ReadAsStringAsync();
                    // MessageBox.Show(retString);
                }
            }
            return responseBody;

        }


        /// <summary>
        /// 使用Get请求异步获取信息
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <returns></returns>
        public static async Task<string> GetStringAsync(string url, string code)
        {

            string responseBody = string.Empty;
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };

            using (var httpclient = new HttpClient(handler))
            {
                httpclient.BaseAddress = new Uri(url);
                httpclient.DefaultRequestHeaders.Accept.Clear();
                httpclient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await httpclient.GetAsync(code);

                if (response.IsSuccessStatusCode)
                {
                    Stream myResponseStream = await response.Content.ReadAsStreamAsync();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    string retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                    responseBody = await response.Content.ReadAsStringAsync();
                    //MessageBox.Show(retString);
                }
            }
            return responseBody;
        }

        #endregion

        #region PUT请求


        /// <summary>
        /// Put请求指定的URL地址
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="putData">提交到Web的Json格式的数据：如:{"ErrCode":"FileErr"}</param>
        /// <returns></returns>
        public static string PutWebAPI(string url, string putData)
        {
            string result = "";
            string strOut = "";
            result = PutWebAPI(url, putData, out strOut);
            return result;
        }

        /// <summary>
        /// Put请求指定的URL地址
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="putData">提交到Web的Json格式的数据：如:{"ErrCode":"FileErr"}</param>
        /// <param name="statusCode">Response返回的状态</param>
        /// <returns></returns>
        public static string PutWebAPI(string url, string putData, out string statusCode)
        {
            string result = statusCode = string.Empty;
            HttpContent httpContent = new StringContent(putData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
                    statusCode = response.StatusCode.ToString();
                    if (response.IsSuccessStatusCode)
                    {
                        result = response.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                       LogHelper.LogWarning("调用后台服务返回失败：" + url + Environment.NewLine);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogWarning("调用后台服务出现异常！", ex);
            }
            return result;
        }
        #endregion

        #region delete请求
        public static async Task<string> DeleteWebAPIAsync(string url, string code)
        {

            string responseBody = string.Empty;
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };

            using (var httpclient = new HttpClient(handler))
            {
                httpclient.BaseAddress = new Uri(url);
                httpclient.DefaultRequestHeaders.Accept.Clear();
                httpclient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await httpclient.DeleteAsync(code);

                if (response.IsSuccessStatusCode)
                {
                    Stream myResponseStream = await response.Content.ReadAsStreamAsync();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    string retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                    responseBody = await response.Content.ReadAsStringAsync();
                    //MessageBox.Show(retString);
                }
            }
            return responseBody;
        }
        #endregion

    }
}
